package com.walnut.servlet;

import com.walnut.dao.UserDao;
import com.walnut.dao.impl.UserDaoImpl;
import com.walnut.pojo.User;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/userInsert")
public class UserInsertServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
        ServletContext context=request.getServletContext();
        request.setCharacterEncoding("UTF-8");
        User user = new User().builder()
                .username(request.getParameter("username"))
                .password(request.getParameter("password"))
                .email(request.getParameter("email"))
                .phone(Long.parseLong(request.getParameter("phone")))
                .build();
        UserDao userDao = new UserDaoImpl();

        try {
            User use=userDao.selectByName(user.getUsername());
            if (use!=null) {
                context.setAttribute("message", "用户名已存在");
                request.getRequestDispatcher("register.jsp").forward(request, response);
            }else {
                context.setAttribute("message", "注册成功");
                userDao.insert(user);
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
